package com.dingreading.cloud.common.util.aliyun;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.AliyunBookDto;
import com.dingreading.cloud.common.util.DateTimeValidator;
import com.dingreading.cloud.common.util.HttpUtils;
import com.dingreading.cloud.common.util.StringUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 阿里云isbn号查询书籍
 */
public class AliyunBookUtil {

    public static void main(String[] args) {
        AliyunBookDto book = findBook("9787547442968");
        System.out.println("book = " + book);
//        R<Object> book = getBook("9787559546586");
//        System.out.println(book);
    }

    /**
     * 查询书籍
     */
    public static AliyunBookDto findBook(String isbn) {
        String host = "https://jisuisbn.market.alicloudapi.com";
        String path = "/isbn/query";
        String method = "GET";
        String appcode = "fbefd53773e640ab923b1d5804a1db9e";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        querys.put("isbn", isbn);

        AliyunBookDto aliyunBookDto = null;
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            String result = HttpUtils.doGet(host, path, method, headers, querys);

            if (StringUtils.isBlank(result))
                return null;

            JSONObject jsonObject = JSONObject.parseObject(result);
            if (null != jsonObject) {
                String status = jsonObject.getString("status");
                if (null != status && status.equals("0")) {
                    //获取response的body
                    aliyunBookDto = JSONObject.parseObject(result, AliyunBookDto.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aliyunBookDto;
    }

    /**
     * 查询书籍
     */
    public static R<AliyunBookDto.ResultDTO> getBook(String isbn) {
        
        String host = "https://jisuisbn.market.alicloudapi.com";
        String path = "/isbn/query";
        String method = "GET";
        String appcode = "fbefd53773e640ab923b1d5804a1db9e";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        querys.put("isbn", isbn);

        AliyunBookDto aliyunBookDto = null;
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            String result = HttpUtils.doGet(host, path, method, headers, querys);
            if (StringUtils.isBlank(result))
                return R.fail("云查询没有找到书籍！isbn：" + isbn);

            JSONObject jsonObject = JSONObject.parseObject(result);
            if (null != jsonObject) {
                String status = jsonObject.getString("status");
                if (null != status && status.equals("0")) {
                    //获取response的body
                    aliyunBookDto = JSONObject.parseObject(result, AliyunBookDto.class);
                }
            }
            if (aliyunBookDto == null)
                return R.fail("云查询没有找到书籍！isbn：" + isbn);

            String status = aliyunBookDto.getStatus();
            if (status == null || !status.equals("0"))
                return R.fail(AliyunBookUtil.getMessage(status));

            AliyunBookDto.ResultDTO resultDto = aliyunBookDto.getResult();
            if (resultDto == null)
                return R.fail("云查询的书籍为null！isbn：" + isbn);

            // 处理出版日期的格式
            String pubDate = resultDto.getPubdate();
            if (StringUtils.isNotBlank(pubDate)) {
                resultDto.setPubdate(pubDateToYmd(pubDate));
            }

            return R.ok(resultDto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail("云查询没有找到书籍！isbn：" + isbn);
    }

    /**
     * 按状态码返回信息
     */
    public static String getMessage(String status) {
        String message = "查询书籍错误";
        if (status != null) {
            if (status.equals("201")) {
                message = "ISBN为空";
            } else if (status.equals("202")) {
                message = "ISBN不正确";
            } else if (status.equals("205")) {
                message = "没有查到书籍，请联系导读员";
            }
        }
        return message;
    }

    /**
     * 去除金额里的中文字符
     */
    public static double getPrice(String price) {
        if (StringUtils.isNotBlank(price)) {
            // 需要取整数和小数的字符串
            // 控制正则表达式的匹配行为的参数(小数)
            Pattern p = Pattern.compile("(\\d+\\.\\d+)");
            //Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例.
            Matcher m = p.matcher(price);
            //m.find用来判断该字符串中是否含有与"(\\d+\\.\\d+)"相匹配的子串
            if (m.find()) {
                //如果有相匹配的,则判断是否为null操作
                //group()中的参数：0表示匹配整个正则，1表示匹配第一个括号的正则,2表示匹配第二个正则,在这只有一个括号,即1和0是一样的
                price = m.group(1) == null ? "" : m.group(1);
            } else {
                //如果匹配不到小数，就进行整数匹配
                p = Pattern.compile("(\\d+)");
                m = p.matcher(price);
                if (m.find()) {
                    //如果有整数相匹配
                    price = m.group(1) == null ? "" : m.group(1);
                } else {
                    //如果没有小数和整数相匹配,即字符串中没有整数和小数，就设为空
                    price = "";
                }
            }
            return Double.parseDouble(price);
        }
        return 0;
    }


//    public static void main(String[] args) {
//        System.out.println(toYmd("2023-01-16"));
//        System.out.println(toYmd("2023-02-2"));
//        System.out.println(toYmd("2023-3-03"));
//        System.out.println(toYmd("2023-4-4"));
//        System.out.println(toYmd("2023-05"));
//        System.out.println(toYmd("2023-6"));
//        System.out.println(toYmd("2023-11"));
//        System.out.println(toYmd("2023"));
//        System.out.println(toYmd("sfjks"));
//        System.out.println(toYmd("哈哈哈"));
//        System.out.println(toYmd("123哈哈哈"));
//        System.out.println(toYmd("1234"));
//        System.out.println(toYmd("123"));
//        System.out.println(toYmd("12345"));
//
//        System.out.println(DateTimeValidator.isValidDate("2021-12-15"));
//        System.out.println(DateTimeValidator.isValidDate("2023-1-16"));
//        System.out.println(DateTimeValidator.isValidDate("2023-01-1"));
//        System.out.println(DateTimeValidator.isValidDate("2023-1-1"));
//        System.out.println(DateTimeValidator.isValidTime("2023-01"));
//    }

    public static String pubDateToYmd(String ymd) {
        // 先判断是不是汉字
        if (StringUtil.isChinese(ymd))
            return "";

        // 没有下划线，并且不是年份
        if (!ymd.contains("-") && ymd.length() != 4)
            return "";

        // 日期格式正确不处理
        boolean validDate = DateTimeValidator.isValidDate(ymd);
        if (!validDate) {
            if (ymd.length() == 4) {
                return ymd + "-01-01";
            } else if (ymd.contains("-")) {
                String[] split = StringUtils.split(ymd, "-");
                if (split.length <= 0)
                    return "";

                List<String> list = Arrays.asList(split);
                int size = list.size();
                if (size == 1) {
                    String s = list.get(0);
                    if (s.length() == 4)
                        return s + "-01-01";
                } else if (size == 2) {
                    String newStr = "";
                    for (int i = 0; i < size; i++) {
                        String s = list.get(i);
                        int length = s.length();
                        if (i == 0) {
                            if (length != 4)
                                return "";
                            newStr += s;
                        } else if (i == 1) {
                            if (length == 1) {
                                newStr += "-0" + s + "-01";
                            } else if (length == 2) {
                                newStr += "-" + s + "-01";
                            } else {
                                newStr += "-01-01";
                            }
                        }
                    }
                    return newStr;
                } else if (size == 3) {
                    String newStr = "";
                    for (int i = 0; i < size; i++) {
                        String s = list.get(i);
                        int length = s.length();
                        if (i == 0) {
                            if (length != 4)
                                return "";
                            newStr += s;
                        } else if (i == 1 || i == 2) {
                            if (length == 1) {
                                newStr += "-0" + s;
                            } else if (length == 2) {
                                newStr += "-" + s;
                            } else {
                                newStr += "-01";
                            }
                        }
                    }
                    return newStr;
                }
            }
        }
        return ymd;
    }

}
